﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Content;

namespace Homebound
{
    class GamePlayState : State
    {
        public bool pause = false;

        // Fonts
        SpriteFont font;
        SpriteFont titleFont;
        SpriteFont hudFont;

        Hud hud;
        
        // We store our input states so that we only poll once per frame, 
        // then we use the same input state wherever needed
        private GamePadState gamePadState;
        private KeyboardState keyboardState;

        // Meta-level game state.
        private int levelIndex = 0;
        public Level level;
        private bool nextEnabled;

        // The number of levels in the Levels directory of our content. We assume that
        // levels in our content are 0-based and that all numbers under this constant
        // have a level file present. This allows us to not need to check for the file
        // or handle exceptions, both of which can add unnecessary time to level loading.
        private const int numberOfLevels = 3;

        public GamePlayState(SpriteFont newFont, SpriteFont newTitleFont, SpriteFont newHudFont, GraphicsDeviceManager newGraphics, GameServiceContainer newServices, ContentManager newContent)
            : base(newGraphics, newServices, newContent)
        {
            font = newFont;
            titleFont = newTitleFont;
            hudFont = newHudFont;
            nextEnabled = true;
            levelIndex = 0;

            loadContent();

            LoadNextLevel();
            hud = new Hud(level, graphics, content);
        }

        // Load the game's external content.
        public override void loadContent()
        {
            // Load overlay textures
            base.loadContent();
        }

        // Called whenever a new state is selected.
        public override void onEnter(State state)
        {
            level.player.lives = 3;
            /*loadContent();
            if (state is LevelSelectState)
            {
                LevelSelectState lsState = (LevelSelectState)state;
                levelIndex = lsState.selectedChoice;
            }
            
            LoadNextLevel();
            try
            {
                MediaPlayer.Resume();
            }
            catch { }
            hud = new Hud(level, graphics, content);*/
            base.onEnter(state);

            // Play BGM
            try
            {
                MediaPlayer.IsRepeating = true;
                MediaPlayer.Play(content.Load<Song>("Sounds/Asphalt_Dawn"));
            }
            catch { }
        }

        // Called when the state is changing.
        public override void onExit(State state)
        {
            try
            {
                MediaPlayer.IsRepeating = true;
                MediaPlayer.Pause();
            }
            catch { }
            base.onExit(state);
        }

        // Draw the visual representation of the state.
        public override void draw(SpriteBatch spriteBatch, GameTime gameTime, Vector2 screenSize)
        {
            if (level != null)
                level.Draw(gameTime, spriteBatch);

            hud.draw(spriteBatch);
        }

        // Handles all input for the current state, (Keyboard, GamePad).
        public override void input(GameTime gameTime, List<Keys> keys, GamePadButtons buttons, GamePadDPad dpad, GamePadThumbSticks thumbSticks)
        {
            // get all of our input states
            keyboardState = Keyboard.GetState();
            gamePadState = GamePad.GetState(PlayerIndex.One);

            if ((keyboardState.IsKeyDown(Keys.F10) || gamePadState.IsButtonDown(Buttons.Start)) && nextEnabled)
            {
                pause = true;
                nextEnabled = false;
            }

            if (keyboardState.IsKeyUp(Keys.F10) && gamePadState.IsButtonUp(Buttons.Start))
            {
                pause = false;
                nextEnabled = true;
            }
        }

        // Handles all update operations for the current state, (Keyboard, GamePad).
        public override void update(GameTime gameTime)
        {
                if (!level.Player.IsAlive)
                {
                    level.StartNewLife();
                }
                else if (level.TimeRemaining == TimeSpan.Zero)
                {
                    if (!level.ReachedExit)
                       LoadNextLevel();
                }

            // update our level, passing down the GameTime along with all of our input states
            level.Update(gameTime, keyboardState, gamePadState, graphics);
            base.update(gameTime);
        }

        private void LoadNextLevel()
        {
            // Load the level.
            string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex);
            using (Stream fileStream = TitleContainer.OpenStream(levelPath))
                level = new Level(services, fileStream, levelIndex, content);
            hud = new Hud(level, graphics, content);
        }

        // Conditions necessary to enter go to a next state.
        public override bool goingBack(State next)
        {
            PauseState pauseState = (PauseState)next;

            return !pauseState.nextEnabled;
        }

        // Conditions necessary to enter go to a next state.
        public override bool goingForward(State prev)
        {
            LevelSelectState levelSelectState = (LevelSelectState)prev;

            if (levelSelectState.enterPressed && levelSelectState.access[levelSelectState.selectedChoice])
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
